package cn.schoolwow.quickdao.module.initial.flow.datasource;

import cn.schoolwow.quickdao.module.initial.flow.database.*;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;

public class CreateDatabaseFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        hikariDataSource(flowContext);
        dynamicRoutingDataSource(flowContext);
    }

    @Override
    public String name() {
        return "创建数据库";
    }

    private void hikariDataSource(FlowContext flowContext){
        DataSource dataSource = flowContext.checkData("dataSource", DataSource.class);

        try {
            ClassLoader.getSystemClassLoader().loadClass("com.zaxxer.hikari.HikariDataSource");
        } catch (ClassNotFoundException e) {
            return;
        }

        if(dataSource instanceof HikariDataSource){
            HikariDataSource hikariDataSource = (HikariDataSource) dataSource;

            flowContext.putTemporaryData("driverClassName", hikariDataSource.getDriverClassName());
            flowContext.putTemporaryData("jdbcUrl", hikariDataSource.getJdbcUrl());
            if(null!=hikariDataSource.getUsername()){
                flowContext.putTemporaryData("username", hikariDataSource.getUsername());
            }
            if(null!=hikariDataSource.getPassword()){
                flowContext.putTemporaryData("password", hikariDataSource.getPassword());
            }
            flowContext.startFlow(new CheckDataSourceFlow())
                    .next(new SetDatabaseNameFlow())
                    .next(new SetQueryDatabaseStatementFlow())
                    .next(new SetCreateDatabaseStatementFlow())
                    .next(new ExecuteCreateDatabaseFlow())
                    .execute();
        }
    }

    private void dynamicRoutingDataSource(FlowContext flowContext){
        DataSource dataSource = flowContext.checkData("dataSource", DataSource.class);

        try {
            ClassLoader.getSystemClassLoader().loadClass("com.baomidou.dynamic.datasource.DynamicRoutingDataSource");
        } catch (ClassNotFoundException e) {
            return;
        }
        if(dataSource instanceof DynamicRoutingDataSource){
            DynamicRoutingDataSource dynamicRoutingDataSource = (DynamicRoutingDataSource) dataSource;

            for(DataSource singleDataSource:dynamicRoutingDataSource.getDataSources().values()){
                flowContext.putCurrentFlowData("dataSource", singleDataSource);
                hikariDataSource(flowContext);
            }
        }
    }
}
